package com.demo.project_template.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.demo.project_template.constant.CommonConstants;
import com.demo.project_template.entity.Address;
import com.demo.project_template.exception.ErrorCodeException;
import com.demo.project_template.exception.ErrorCodeExceptionEnum;
import com.demo.project_template.mapper.AddressMapper;
import com.demo.project_template.service.AddressService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.demo.project_template.util.CheckEmptyUtil;
import com.demo.project_template.util.GaoDeUtil;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;

/**
 * <p>
 * 地址表 服务实现类
 * </p>
 *
 * @author 杨玉龙
 * @since 2023-06-19 15:56:43
 */
@Service
public class AddressServiceImpl extends ServiceImpl<AddressMapper, Address> implements AddressService {

    @Resource
    private AddressMapper addressMapper;

    /**
     * 用户增加地址
     *
     * @param address 地址对象
     */
    @Override
    @Transactional(rollbackFor = RuntimeException.class)
    public void userInsertAddress(Address address) {
        if (address.getAddressStatus().equals(CommonConstants.DEFAULT)) {
            Address updateAddress = new Address();
            updateAddress.setAddressStatus(CommonConstants.ENABLE);
            addressMapper.update(updateAddress, new LambdaQueryWrapper<Address>().eq(Address::getUserId, address.getUserId()));
        }
        int insertTotal = addressMapper.insert(address);
        if (insertTotal == 0) {
            throw new ErrorCodeException(ErrorCodeExceptionEnum.ABNORMAL_OPERATION);
        }
    }

    /**
     * 用户修改地址
     *
     * @param address 地址对象
     */
    @Override
    @Transactional(rollbackFor = RuntimeException.class)
    public void userUpdateAddress(Address address) {
        if (!CheckEmptyUtil.isEmpty(address.getAddressStatus()) && address.getAddressStatus().equals(CommonConstants.DEFAULT)) {
            Address updateAddress = new Address();
            updateAddress.setAddressStatus(CommonConstants.ENABLE);
            addressMapper.update(updateAddress, new LambdaQueryWrapper<Address>().eq(Address::getUserId, address.getUserId()));
        }
        int updateTotal = addressMapper.updateById(address);
        if (updateTotal == 0) {
            throw new ErrorCodeException(ErrorCodeExceptionEnum.ABNORMAL_OPERATION);
        }
    }
}
